package com.konsung.ksdc.manager.community;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.netbean.GroupNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.service.MqttService;

import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by liangkun on 2017/5/17 0017.
 * 确认是否加入群聊
 */

public class JionGoupActivity extends AppCompatActivity {
    @Bind(R.id.iv_group_head)
    protected ImageView ivHead;
    @Bind(R.id.tv_group_name)
    protected TextView tvName;
    @Bind(R.id.tv_all_count)
    protected TextView tvCount;
    @Bind(R.id.btn_join_group)
    protected Button btnJion;
    @Bind(R.id.img_back)
    protected ImageView ivBack;
    private String data;
    private GroupNetBean bean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jion_group);
        ButterKnife.bind(this);
        initData();
        initView();
        initEvent();
    }

    /**
     * 数据
     */
    private void initData() {
        data = getIntent().getStringExtra("data");
        bean = new Gson().fromJson(data, GroupNetBean.class);
    }

    /**
     * UI
     */
    private void initView() {
        Glide.with(this).load(StringUtils.appendPicPath(bean.getGroupPic())).into(ivHead);
        tvName.setText(bean.getGroupName());
        tvCount.setText(bean.getUsers().size() + "");
    }

    /**
     * 加入群事件
     */
    private void initEvent() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnJion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!RequestUtils.isNetworkConnected(JionGoupActivity.this)
                        || !MqttService.isMqttConnected()) {
                    ToastUtils.toastContent(JionGoupActivity.this, getString(R.string
                            .chat_unconnect));
                    return;
                }
                RequestUtils.jionGroup(bean.getGroupId(), NetConfig.currentUser.getUserId(), new
                        RequestCallback() {

                            @Override
                            public void onError(Call call, Exception e) {
                                ToastUtils.toastContent(JionGoupActivity.this, getString(R.string
                                        .chat_unconnect));
                            }

                            @Override
                            public void onResponse(ResponseBean responseBean) {
                                String msg = responseBean.getEntity(String.class);
                                if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                                    //成功后发送群消息让扫码用户订阅，同时让其他成员也能看到该成员

                                    sendAddGroupMessage(bean.getGroupId());
                                    Intent intent = new Intent(JionGoupActivity.this,
                                            GroupChatActivity.class);
                                    intent.putExtra("topicName", bean.getGroupId()); //群id
                                    intent.putExtra("groupName", bean.getGroupName());
                                    startActivity(intent);
                                    ToastUtils.toastContent(JionGoupActivity.this, msg);
                                    finish();
                                } else {
                                    ToastUtils.toastContent(JionGoupActivity.this, msg);
                                }
                            }
                        });
            }
        });
    }

//    /**
//     * 发送群消息给群里的人
//     * @param groupNetBean 群组信息
//     */
//    private void sendAddGroupMessage(GroupNetBean groupNetBean) {
//        //循环发送
//        for (RegisterUserNetBean netBean : groupNetBean.getUsers()) {
//            String msgSendDate = DateUtils.getStringDateFormat(new Date(),
//                    DateUtils.yyyyMMddHHmmss);
//            String targetType = MqttMsgUtils.MSG_TARGET_TYPE_GROUP;
//            MqttMsgBean bean = new MqttMsgBean();
//            bean.setMsgContent(groupNetBean.getGroupId());
//            bean.setMsgSendDate(msgSendDate);
//            bean.setMsgTargetType(targetType);
//            bean.setMsgType(MqttMsgUtils.MSG_TYPE_REQUEST_GROUP);
//            bean.setContact(NetConfig.currentUser.getUserId());
//            bean.setTopicName(netBean.getUserName());
//            try {
//                byte[] msgContent = MqttMsgUtils.msgBeanParseByte(bean);
//                MqttService.mqttClient.publish(bean.getTopicName(), msgContent, 2, false);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

    /**
     * 发送群消息给群里的人
     * @param groupId id
     */
    private void sendAddGroupMessage(final String groupId) {
        RequestUtils.findCommunityById(groupId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                ToastUtils.toastContent(JionGoupActivity.this, getString(R.string.chat_faile));
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                GroupNetBean group = responseBean.getEntity(GroupNetBean.class);

                for (RegisterUserNetBean user : group.getUsers()) {
                    String msgSendDate = DateUtils.getStringDateFormat(new Date(),
                            DateUtils.yyyyMMddHHmmss);
                    String targetType = MqttMsgUtils.MSG_TARGET_TYPE_GROUP;
                    MqttMsgBean bean = new MqttMsgBean();
                    bean.setMsgContent(groupId);
                    bean.setMsgSendDate(msgSendDate);
                    bean.setMsgTargetType(targetType);
                    bean.setMsgType(MqttMsgUtils.MSG_TYPE_REQUEST_GROUP);
                    bean.setContact(NetConfig.currentUser.getUserId());
                    bean.setTopicName(user.getUserName());

                    try {
                        byte[] msgContent = MqttMsgUtils.msgBeanParseByte(bean);
                        MqttService.mqttClient.publish(bean.getTopicName(), msgContent, 2, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

